package cn.xiaobai.handler.redis;

import cn.xiaobai.domain.RedisConfInfo;
import cn.xiaobai.monitor.MonitorServer;
import cn.xioabai.common.utility.JsonUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;
import java.util.Objects;

/**
 * 通用redis 服务端, 处理数据推送
 *
 * @Author yangdaji
 * @Date 2022/11/15 0015
 * @PackageName cn.xiaobai.service.redis
 * @ClassName GeneralRedisServer
 */
@Slf4j
@Component
public class RedisPushDataHandler {

    private Jedis jedis;

    private JedisPool jedisPool;

    @Autowired
    private MonitorServer monitorServer;

    /**
     * 初始化redis 线程池
     */
    private void initRedisPool() {
        if (RedisConfInfo.isUse()) {
            log.info("装配redis 连接池...");
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setTestOnBorrow(true);
            jedisPoolConfig.setTestOnReturn(true);


            String password = RedisConfInfo.password;
            jedisPool = new JedisPool(jedisPoolConfig, RedisConfInfo.host, RedisConfInfo.port,
                    10000, StringUtils.isBlank(password) ? null : password);

            try {
                jedis = jedisPool.getResource();
                log.info("获取连接资源....");
            } catch (Exception e) {
                log.info("获取连接资源失败: {}", e.getMessage());
            }
        }
    }

    /**
     * 开始推送
     */
    public void startPush() {
        initRedisPool();
//        log.info("开始往redis 推送数据....");
    }

    /**
     * 推送到redis
     */
    @Scheduled(cron = "* * * * * *")
    public void redisPush() {

        Map<String, Object> channelToDataMap = monitorServer.getChannelToDataMap();
        if (CollectionUtils.isEmpty(channelToDataMap) || Objects.isNull(jedis)) {
//            log.info("没有获取到需要推送的数据....");
            return;
        }

        channelToDataMap
                .forEach((key, value) -> jedis.publish(key,
                        JsonUtils.toJsonStr(value))
                );
    }
}
